<?php

namespace app\model;

use think\model\relation\BelongsTo;

class AdminSchoolDevice extends Base
{
    const SERIAL_TYPE = [1 => '门禁', 2 => '人脸一体机'];

    public function school(): BelongsTo {
        return $this->belongsTo(AdminSchool::class, 'school_id')->where(['is_delete' => 0])->bind([
            'school_name' => 'name'
        ]);
    }

    public function getSerialTypeTextAttr($value, $data)
    {
        $type = self::SERIAL_TYPE;
        return $type[$data['serial_type']] ?? '';
    }

    public function getHeartTimeAttr($value) {
        return $value > 0 ? date('Y-m-d H:i:s', $value) : '';
    }

    /**
     * 获取单条记录
     * @param $serial
     * @return AdminSchoolDevice|array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getOneData($serial)
    {
        return self::where('serial', $serial)->find();
    }

    /**
     * 获取指定学校的所有人脸设备
     * @param $school_id
     * @return AdminSchoolDevice[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getFaceBySchoolList($school_id = 0)
    {
        $where['serial_type'] = 2;
        if($school_id > 0){
            $where['school_id'] = $school_id;
        }
        return self::field('sd_id,serial,device_id')->where($where)->select();
    }
}
